<?php
/**
 * 图像识别相关
 * @author zxr
 * @time 20180719
 */
namespace App\Libraries;
class shitu {


    public function __construct()
    {
    }

    /**
     * 获取授权token
     */
    public function getToken(){

        $data['username'] = env('imageRecognition_username');
        $data['password'] = env('imageRecognition_password');
        $url              = env('imageRecognition_getToken_url');

        $curl = new curl();
        $tokenInfo = $curl->post($url,$data);//发送请求
        $arr_token = json_decode($tokenInfo,true);
        //加入失效时间
        $arr_token['outTime'] = time()+$arr_token['expires_in']-5;

        //获取的token 存入文件
        $this->set_php_file(storage_path('data/imageRecognition_token.php'), json_encode($arr_token));

        return $arr_token;
    }

    /**
     * 刷新token
     * @param $access_token
     * @return mixed
     */
    public function refreshToken($access_token){

        $url = env('imageRecognition_refreshToken_url');
        $header = [
            'Authorization:Bearer '.$access_token,
        ];
        $curl = new curl();
        $tokenInfo = $curl->put($url,'','','',$header);
        $arr_token = json_decode($tokenInfo,true);

        if (isset($arr_token['status_code']) && $arr_token['status_code'] == 401 ) {
            $arr_token = $this->getToken();
        }
        //加入失效时间
        $arr_token['outTime'] = time()+$arr_token['expires_in']-5;

        //获取的token 存入文件
        $this->set_php_file(storage_path('data/imageRecognition_token.php'), json_encode($arr_token));
        return $arr_token;

    }

    public function sendCrops($imgUrl,$type){

        //获取文件中的token
        $tokenInfo = json_decode($this->get_php_file(storage_path('data/imageRecognition_token.php')),true);
//        print_r($tokenInfo);die;

        if($tokenInfo['access_token']){
            if(time() > $tokenInfo['outTime']){
                $tokenInfo =$this->refreshToken($tokenInfo['access_token']);
            }
        }else{
            $tokenInfo = $this->getToken();
        }

        //调用作物对比接口
        $url = env('imageRecognition_Url_v2');
        $data = [
            'url' => $imgUrl,
            'type' => $type,
        ];
        $header = [
            'Authorization:Bearer '.$tokenInfo['access_token'],
        ];
        $curl = new curl();
        $cropsInfo = $curl->post($url,$data,'','',$header);
        $cropsInfo = json_decode($cropsInfo,true);
        return $cropsInfo;
    }

    /**
     * 写入文件
     */
    private function set_php_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }

    /**
     * 获取文件
     */
    private function get_php_file($filename) {
        return trim(substr(file_get_contents($filename), 15));
    }



}